<template>
  <el-card>
    <div>
      <span class="iconfont icon-http custom-icon">Request</span>
      <el-tabs
        v-model="editableTabsValue"
        type="card"
        editable
        @edit="handleTabsEdit"
      >
        <el-tab-pane
          :key="item.name"
          v-for="item in editableTabs"
          :label="item.title"
          :name="item.name"
        >
          <RequestSender :requestData="item.requestData" />
        </el-tab-pane>
      </el-tabs>
    </div>
  </el-card>
</template>

<script>
import { EventBus } from '@/event-bus.js';  // 引入事件总线
import RequestSender from './RequestSender.vue';

export default {
  components: {
    RequestSender
  },
  data() {
    return {
      editableTabsValue: '1',
      editableTabs: [
        {
          title: 'New Request',
          name: '1',
          requestData: { method: 'GET', url: '' }  // 默认数据
        }
      ],
      tabIndex: 1
    };
  },
  created() {
    // 监听 openRequestTab 事件
    EventBus.$on('openRequestTab', (row) => {
      this.addTab(row);  // 根据传入的 row 数据创建新标签页
    });
  },
  destroyed() {
    // 组件销毁时移除监听
    EventBus.$off('openRequestTab');
  },
  methods: {
    handleTabsEdit(targetName, action) {
      if (action === 'add') {
        const newTabName = `${++this.tabIndex}`;
        const newTabData = {
          title: 'New Request',
          name: newTabName,
          requestData: { method: 'GET', url: '' }
        };
        this.editableTabs.push(newTabData);
        this.editableTabsValue = newTabName;
      } else if (action === 'remove') {
        const tabs = this.editableTabs;
        let activeName = this.editableTabsValue;
        if (activeName === targetName) {
          tabs.forEach((tab, index) => {
            if (tab.name === targetName) {
              const nextTab = tabs[index + 1] || tabs[index - 1];
              if (nextTab) {
                activeName = nextTab.name;
              }
            }
          });
        }
        this.editableTabsValue = activeName;
        this.editableTabs = tabs.filter((tab) => tab.name !== targetName);
      }
    },
    // 添加新标签页
    addTab(row) {
      const newTabName = `${++this.tabIndex}`;
      const newTabData = {
        title: row.name,  // 使用 row 数据中的 name 作为 tab 的标题
        name: newTabName,
        requestData: { method: 'GET', url: row.url,body: row.body }  // 传递 row 中的数据给 RequestSender
      };
      this.editableTabs.push(newTabData);
      this.editableTabsValue = newTabName;
    }
  }
};
</script>

<style scoped>
.custom-icon {
  margin-left: 15px;
  font-size: 24px;
  margin-bottom: 16px;
  color: #008000;
}
</style>
